package com.globallogic.socialnetwork.util;

import net.sourceforge.jwebunit.junit.WebTester;
import net.sourceforge.jwebunit.util.TestingEngineRegistry;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
import org.springframework.test.context.ContextConfiguration;

/**
 * Embedded container used to run the application. Tweaks jetty so that it can
 * find inner jars, since maven is using another classloading way than eclipse.
 * Before web application loads it adds all the jars from manifest only jar
 * file. You can read more about maven classloading and manifestonly jars and
 * why they are needed at <a href=
 * 'http://maven.apache.org/plugins/maven-surefire-plugin/examples/class-loading.html'>mav
 * e n site</a>
 */


public class JettyContainer {

	private static final int PORT = 1234;
	private static final String CONTEXT_ROOT = "/" + Constants.TRAINEE_SURNAME
			+ "-SocialNetwork";
	public static final String URL = "http://localhost:" + PORT + CONTEXT_ROOT;
	private static Server server;
	private static WebTester tester;

	public JettyContainer() {
	}

	public static WebTester getTester() throws Exception {
		if (tester == null) {
			// configure jetty
			WebAppContext context = new WebAppContext("src/main/webapp",
					CONTEXT_ROOT);
			server = new Server(PORT);
			server.setHandler(context);
			// start jetty
			server.start();
			// setting web tester and its web context
			int port = server.getConnectors()[0].getLocalPort();
			tester = new WebTester();
			tester.setTestingEngineKey(TestingEngineRegistry.TESTING_ENGINE_HTMLUNIT);
			tester.getTestContext().setBaseUrl(
					"http://localhost:" + port + CONTEXT_ROOT);
		}
		return tester;
	}

	public static void join() throws InterruptedException {
		if (server != null)
			server.join();
	}

	public static void stop() throws Exception {
		if (server != null)
			server.stop();
	}
}
